﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using YlisChat.Models;

namespace YlisChat.DAO
{
    public class MessageDAO
    {
        // Statig methods
        private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static List<Action<Discussion>> MessageSubscribers = new List<Action<Discussion>>();
        public static void Subscribe(Action<Discussion> subscriber)
        {
            MessageSubscribers.Add(subscriber);
        }

        // Normal methods

        private ApplicationDbContext db;

        public MessageDAO(ApplicationDbContext DbContext)
        {
            this.db = DbContext;
        }

        /// <summary>
        /// Sends a system message to a channel
        /// </summary>
        /// <param name="Message">The messsage text content</param>
        /// <param name="Channel">The channel message is sent to</param>
        /// <param name="UserId">The message relates to this user</param>
        public void SendSystemMessage(string Message, string Channel, string UserId = null)
        {
            if(String.IsNullOrWhiteSpace(Message) || String.IsNullOrWhiteSpace(Channel))
            {
                Log.Error("MessageDAO.SendSystemMessage: empty message or channel.");
                return;
            }
            Discussion msg = new Discussion()
            {
                UserId = UserId,
                HashTag = Channel,
                Message = Message,
                TimeStamp = DateTime.UtcNow,
                SystemMessage = true,
                Id = Guid.NewGuid().ToString()
            };
            SendMessage(msg);
        }

        public async Task SendMessage(Discussion Msg)
        {
            if (Msg == null)
            {
                Log.Error("MessageDAO.SendMessage: msg is null.");
                return;
            }

            foreach (Action<Discussion> Subscriber in MessageSubscribers)
            {
                Subscriber.Invoke(Msg);
            }

            db.Discussion.Add(Msg);
            await db.SaveChangesAsync();
        }
    }
}